//
//  OrientationViewController.swift
//  iPhone
//
//  Created by Toj on 6/13/23.
//

import UIKit

class OrientationViewController: UIViewController {
    
    
    override var shouldAutorotate: Bool {
        print("-->toj: or func: \(#function)")
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .allButUpsideDown
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        // 屏幕旋转Notification
        NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange(noti:)), name: UIDevice.orientationDidChangeNotification, object: nil)
        
        view.backgroundColor = .random
        
        var _ = UIApplication.shared.app_orientation
        let orientation = UIDevice.current.orientation
        
        print("-->toj: ___ viewDidLoad dev orientation:\(orientation.rawValue)")
        print("-->toj: ___ viewDidLoad currentFrame:\(view.frame)")
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        var orientation2 = UIApplication.shared.app_orientation
        let orientation = UIDevice.current.orientation
        
        if orientation2.isLandscape != orientation.isLandscape {
            UIApplication.shared.app_setOrientation(interface: orientation.do_toInterfaceOrientation, viewController: self)
        }
        
        orientation2 = UIApplication.shared.app_orientation

        print("-->toj: ~~~ viewDidAppear dev orientation:\(orientation.rawValue)")
        print("-->toj: ~~~ viewDidAppear currentFrame:\(view.frame)")
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        let _ = UIApplication.shared.app_orientation
        let orientation = UIDevice.current.orientation
        
        print("-->toj: +++ viewWillLayoutSubviews dev orientation:\(orientation.rawValue)")
        print("-->toj: +++ viewWillLayoutSubviews currentFrame:\(view.frame)")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        let _ = UIApplication.shared.app_orientation
        let orientation = UIDevice.current.orientation
        
        print("-->toj: *** viewDidLayoutSubviews dev orientation:\(orientation.rawValue)")
        print("-->toj: *** viewDidLayoutSubviews currentFrame:\(view.frame)")
    }
    
    // 屏幕旋转的通知
    @objc func orientationDidChange(noti:NSNotification) {
        guard shouldAutorotate else { return }
        print("-->toj: BasePlayerController func: orientationDidChange")
    }
}
